package com.test.followme;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import com.test.user.OwnUser;
import com.test.utilities.Utility;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener
{
	private Button btnLogin;
	private Button btnLinkToRegister;
	private EditText txtloginEmail;
	private EditText txtloginPwd;
	private TextView txtloginErr;
	private CheckBox chkRememberMe;
	private TextView lblUserName;
	private EditText txtUserName;
	private TextView lblHeader;
	public String rspMsg;
	public int retCode;
	public boolean isLoginBtn;
	private boolean isThreadUp;
	OwnUser me;
	
	public Context context;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		initialize();	
	}
	
	private void initialize()
	{
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
		txtloginEmail = (EditText) findViewById(R.id.txtloginEmail);
		txtloginPwd = (EditText) findViewById(R.id.txtloginPwd);
		txtloginErr = (TextView) findViewById(R.id.txtloginErr);
		chkRememberMe = (CheckBox) findViewById(R.id.chkRememberMe);
		lblUserName = (TextView) findViewById(R.id.lblUserName);
		txtUserName = (EditText) findViewById(R.id.txtUserName);
		lblHeader = (TextView) findViewById(R.id.lblHeader);
		
		lblUserName.setVisibility(View.INVISIBLE);
		txtUserName.setVisibility(View.INVISIBLE);
		
		btnLogin.setOnClickListener(this);
		btnLinkToRegister.setOnClickListener(this);
		
		context = getApplicationContext();
		
		isLoginBtn = true;
		isThreadUp = false;
		rspMsg = "";
		retCode = 0;
		me = new OwnUser();
		me.setOnline(Boolean.valueOf(Utility.getSharedPrefs(context, Globals.PREFS_ONLINE_STATUS)));
		
		if (Utility.getSharedPrefs(context, Globals.PREFS_CHK_REMEMBER).equals("true"))
		{
			txtloginEmail.setText(Utility.getSharedPrefs(context, Globals.PREFS_EMAIL));
			chkRememberMe.setChecked(true);
		}
				
		getRegId();
	}
	
	@Override
	public void onClick(View v)
	{
		int id = v.getId();
		
		if (id == R.id.btnLogin)
		{
			try
			{
				txtloginErr.setText("");
				fillOwnUser();
				
				if (!validateFields())
				{
					return;
				}
				
				saveChkRememberMe();
				
				execute(v);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		else if (id == R.id.btnLinkToRegisterScreen)
		{
			toggleStatus(v);
		}
	}
	
	private void saveChkRememberMe()
	{
		Utility.addSharedPrefs(context, Globals.PREFS_CHK_REMEMBER, String.valueOf(chkRememberMe.isChecked()));
		Utility.addSharedPrefs(context, Globals.PREFS_EMAIL, me.getMail());
	}
	
	private void fillOwnUser()
	{
		me.setMail(txtloginEmail.getText().toString());
		me.setPwd(txtloginPwd.getText().toString());
		me.setName(txtUserName.getText().toString());
		
		Log.i("fillOwnUser", "mail:" + me.getMail());
		Log.i("fillOwnUser", "pwd:" + me.getPwd());
		Log.i("fillOwnUser", "name:" + me.getName());
	}
	
	public void execute(View v) throws Exception
	{	
		HttpLogin httpLogin = new HttpLogin(this);
		
		httpLogin.httpReq();
		httpLogin.stopHttpReq();

		postExecute();
		
	}
	
	public void toggleStatus(View v)
	{
		isLoginBtn = !isLoginBtn;
		lblUserName.setVisibility(isLoginBtn ? View.INVISIBLE : View.VISIBLE);
		txtUserName.setVisibility(isLoginBtn ? View.INVISIBLE : View.VISIBLE);
		
		btnLogin.setText(isLoginBtn ? "LOGIN" : "REGISTER");
		lblHeader.setText(isLoginBtn ? "LOGIN" : "REGISTER");
		btnLinkToRegister.setText(isLoginBtn ? "I don't have account. Register Me!" : "Return to Login screen");
	}
	
	private void getRegId()
	{
		RegId reg = new RegId(context);
		reg.register2GCM();
		
		if (reg.getRegid() == null)
		{
			reg.register2GCM();
			
			if (reg.getRegid() == null)
			{
				Toast.makeText(this, "You can not registered", Toast.LENGTH_LONG).show();
				finish();
			}
		}
		
		me.setGcmRegId(reg.getRegid());
	}
	
	public List<NameValuePair> fillParams(OwnUser me)
	{
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		
		if (isLoginBtn)
		{
			Log.i("fillParams", "login regid:" + me.getGcmRegId());
			params.add(new BasicNameValuePair(Globals.keyGCM_REGID, me.getGcmRegId()));
		}
		else
		{
			Log.i("fillParams", "register name:" + me.getName());
			params.add(new BasicNameValuePair(Globals.keyUSERNAME, me.getName()));
		}
		
		params.add(new BasicNameValuePair(Globals.keyEMAIL, me.getMail()));
		params.add(new BasicNameValuePair(Globals.keyPASSWORD, me.getPwd()));
		params.add(new BasicNameValuePair(Globals.keyAUTH_KEY, Globals.AUTH_KEY));
		params.add(new BasicNameValuePair(Globals.keyPAGE, isLoginBtn ? Globals.pageLOGIN : Globals.pageREGISTER));
		
		Log.i("fillParams", "mail:" + me.getMail());
		Log.i("fillParams", "pwd:" + me.getPwd());
		Log.i("fillParams", "authkey:" + Globals.AUTH_KEY);
		Log.i("fillParams", "page:" + (isLoginBtn ? Globals.pageLOGIN : Globals.pageREGISTER));
		
		return params;
	}
	
	private boolean validateFields()
	{
		boolean retVal = true;
		
		if (!Utility.isValidEmail(me.getMail()))
		{
			retVal = false;
			txtloginEmail.setError("Invalid Email");
		}
		
		if (!Utility.isValidPassword(me.getPwd()))
		{
			retVal = false;
			txtloginPwd.setError("Invalid Password");
		}
		
		if (!isLoginBtn && Utility.isNullOrEmpty(me.getName()))
		{
			retVal = false;
			txtUserName.setError("Username empty");
		}
		
		return retVal;
	}
	
	private void postExecute()
	{
		if (retCode == Globals.retCodeSuccess && isLoginBtn)
		{
			Toast.makeText(context, "OK Retcode : " + retCode + "\nisLoginBtn: " + isLoginBtn, Toast.LENGTH_LONG).show();
			
			Intent mainMap = new Intent(getApplicationContext(), MainMap.class);
			mainMap.putExtra("OwnUser", me);
			startActivity(mainMap);
		}
		else 
		{
			if (isLoginBtn)
			{
				Toast.makeText(context, "NOK Retcode : " + retCode + "\nisLoginBtn: " + isLoginBtn, Toast.LENGTH_LONG).show();	
			}
			
			txtloginErr.setText(rspMsg);
		}
	}
	
	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		Globals.isWorking = false;
		finish();
	}
}

class HttpLogin
{
	private Thread req;
	LoginActivity loginActivity;
	
	public HttpLogin(LoginActivity loginActivity)
	{
		this.loginActivity = loginActivity;
	}
	
	public void httpReq()
	{
		req = new Thread()
		{
			public void run()
			{
				try
				{					
					try
					{
						JSONObject json = Utility.httpRequest(loginActivity.fillParams(loginActivity.me));
						
						loginActivity.retCode = json.getInt(Globals.keyRETCODE);
						Log.i("HttpLogin", "retCode:" + loginActivity.retCode);
						if (loginActivity.retCode == Globals.retCodeSuccess)
						{
							Log.i("HttpLogin", "retCode is success..");
							
							Utility.addSharedPrefs(loginActivity.context, Globals.PREFS_PWD, loginActivity.me.getPwd());
							
							if (!loginActivity.isLoginBtn)
							{
								Utility.addSharedPrefs(loginActivity.context, Globals.PREFS_USER_NAME, loginActivity.me.getName());
							}
							
							if (loginActivity.isLoginBtn)
							{
								loginActivity.me.setId(json.getString(Globals.keyUSERID));
								loginActivity.me.setSsnId(json.getString(Globals.keySESSIONID));
								loginActivity.me.setName(json.getString(Globals.keyUSERNAME));
								
								Utility.addSharedPrefs(loginActivity.context, Globals.PREFS_USER_ID, loginActivity.me.getId());
								Utility.addSharedPrefs(loginActivity.context, Globals.PREFS_SESSION_ID, loginActivity.me.getSsnId());
								Utility.addSharedPrefs(loginActivity.context, Globals.PREFS_USER_NAME, loginActivity.me.getName());
							}
						}
						else
						{
							Log.i("HttpLogin", "retCode: error");
							loginActivity.rspMsg = json.getString(Globals.keyRETDESC);
							Log.i("requestInBackground", "rspMsg:" + loginActivity.rspMsg);
						}
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
					
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		};
		
		req.start();	
	}
	
	public void stopHttpReq()
	{
		Log.i("HttpLogin", "stopHttpReq()");
		
		while (req.isAlive())
		{
//			Log.i("HttpLogin", "isAlive");
		}
		
		Log.i("HttpLogin", "is not Alive");
	}	
}






























